/* components */
import BizTableTask from '@src/component/business/BizTable/BizTableTask'
import BaseListForNoData from '@src/component/common/BaseListForNoData/index.vue'
import { FormBuilderTableColumnsView } from '@src/component/form/form-builder-table/components';
/* model */
import { 
  ConnectorCardInfo,
  ConnectorCardMultiFixedFieldNameEnum, 
  ConnectorCardMultiFixedFields, 
  ConnectorField, 
  ConnectorFieldTypeEnum, 
  ConnectorModuleComponentNameEnum 
} from '@src/modules/connector/model'
import LoginUser from '@model/entity/LoginUser/LoginUser'
import TaskAddress from '@model/entity/TaskAddress'
import Column from '@model/types/Column';
/* hooks */
import { useConnectorCard } from '@src/modules/connector/hooks'
import { useFormBuilderTableEdit } from '@src/component/form/form-builder-table/hooks';
/* scss */
import '@src/component/form/form-builder-table/index.scss';
import '@src/modules/connector/components/connector-card/multi-card-table.scss'
/* vue */
import { ComponentInstance, ComponentRenderProxy, computed, ComputedRef, defineComponent, PropType, getCurrentInstance, CreateElement, VNode } from 'vue'
import { CommonComponentInstance } from '@model/VC'
/* service */
import { getFieldName, isSystemFiled } from '@service/FieldService'
/* util */
import { isArray, isElement, isNotArray, isObject } from '@src/util/type'
import { formatFormFieldItem } from '@src/filter/form'
import { isOpenData } from '@src/util/platform'
import { fmt_datetime } from '@src/filter/fmt'
import { openTabForCustomerView, openTabForProductView, openTabForTaskView } from '@src/util/business/openTab'
/* types */
import { ConnectorServerValueCustomerType, ConnectorServerValueProductType, ConnectorServerValueRelatedCustomersType } from '@src/modules/connector/types'
import { FieldTypeMappingEnum, TaskFieldNameMappingEnum } from '@model/enum/FieldMappingEnum'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum';

import { t } from '@src/locales'
const TableColumnDefaultWidth = '160px'

export type ConnectorModuleConnectorCardMultiCardTableProps = {
  fields: ConnectorField[];
  loading: boolean;
  values: Record<string, any>[];
  showDeleteButton: boolean;
  showIndex: boolean;
  isMulti: boolean;
  formTableColumns: Column[];
}

export interface ConnectorModuleConnectorCardMultiCardTableSetupState {
  
}

export enum ConnectorModuleConnectorCardMultiCardTableEmitEventNameEnum {
  Delete = 'delete',
}

export type ConnectorModuleConnectorCardMultiCardTableInstance = ComponentInstance & ConnectorModuleConnectorCardMultiCardTableSetupState
export type ConnectorModuleConnectorCardMultiCardTableVM = ComponentRenderProxy<ConnectorModuleConnectorCardMultiCardTableProps> & CommonComponentInstance & ConnectorModuleConnectorCardMultiCardTableInstance

export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorModuleConnectorCardComponentTable,
  components: {
    BizTableTask
  },
  emits: [
    ConnectorModuleConnectorCardMultiCardTableEmitEventNameEnum.Delete,
  ],
  props: {
    fields: {
      type: Array as PropType<ConnectorField[]>,
      default: () => ([])
    },
    loading: {
      type: Boolean as PropType<boolean>,
      default: true
    },
    mainModuleValue: {
      type: Object as PropType<Record<string, any>>,
      default: () => ({})
    },
    values: {
      type: Array as PropType<Record<string, any>[]>,
      default: () => ([])
    },
    showDeleteButton: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    showIndex: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    isMulti: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    formTableColumns: {
      type: Array as PropType<Column[]>,
      default: () => [],
    },
  },
  computed: {
    tableValues () {
      if(!this.values) return [];
      if(isObject(this.values)) return [this.values];
      return this.values;
    } 
  },
  setup(props: ConnectorModuleConnectorCardMultiCardTableProps, { emit }) {
    const onConnectorCardItemDeleteHandler = (row: Record<string, any>) => {
      emit(ConnectorModuleConnectorCardMultiCardTableEmitEventNameEnum.Delete, row)
    }

    const currentInstance = getCurrentInstance();
    const instance = currentInstance?.proxy;
    const columns = computed(() => props?.formTableColumns || []);

    const { onTableCellClickHandler, lastClickTableCellData } = useFormBuilderTableEdit(columns, instance);

    return {
      onConnectorCardItemDeleteHandler,
      onTableCellClickHandler,
      lastClickTableCellData,
    }
  },
  mounted() {
    this.$eventBus.$on('toggleRowSelection', this.toggleRowSelection)
  },
  methods: {
    randomStr() {
      return Math.random().toString(36).substr(2, 9);
    },
    /** 
     * @description 渲染表格插入 用于无限加载显示
    */
    renderTableAppendSlot() {
      return (
        <div class={ this.loading ? 'block-hide' : 'block-show'}>
          <BaseListForNoData  notice-msg={t('common.base.tip.noData')}></BaseListForNoData>
        </div>
      )
    },
    /** 
     * @description 渲染表格列
    */
    renderTableColumnField(h: CreateElement, scope: any, column: ConnectorField) {
      // 渲染业务列
      const renderColumnWithBusinessValue = this.renderColumnWithBusiness(column, scope.row)
      
      // 已经是元素 直接返回
      if (isElement(renderColumnWithBusinessValue)) {
        return renderColumnWithBusinessValue
      }
      
      return (
        <div class='biz-table-cell'>
          { renderColumnWithBusinessValue }
        </div>
      )
      
    },
    /**
     * @description: 渲染业务字段
     * @param {ConnectorField} column 列
     * @param {any} row 行数据
     * @return {VNode} 元素
     */ 
    renderColumnWithBusiness(column: ConnectorField, row: any): VNode | JSX.Element | string | null {
      
      // @ts-ignore
      const formType = column.formType || column.fieldType
      
      // 用户名
      if (column.fieldName == ConnectorCardMultiFixedFieldNameEnum.UserName) {
        
        const value = row[column.fieldName]
        const staffId = row.staffId
        
        return this.renderUserName(value, staffId)
      }
      
      // 编号
      if (formType == ConnectorFieldTypeEnum.SerialNumber || formType == TaskFieldNameMappingEnum.TaskNo) {
        return this.renderColumnWithSerialNumber(column, row)
      }
      
      // 客户
      if (formType == ConnectorFieldTypeEnum.Customer) {
        return this.renderColumnWithCustomer(column, row)
      }
      
      // 关联客户
      if (formType == ConnectorFieldTypeEnum.RelatedCustomers) {
        return this.renderColumnWithRelatedCustomers(column, row)
      }
      
      // 关联工单
      if (formType == ConnectorFieldTypeEnum.RelatedTask || formType == ConnectorFieldTypeEnum.RelationTask) {
        return this.renderColumnWithRelatedTasks(column, row)
      }
      
      // 产品
      if (formType == ConnectorFieldTypeEnum.Product) {
        return this.renderColumnWithProduct(column, row)
      }
      
      // 客户地址
      if (formType == ConnectorFieldTypeEnum.CustomerAddress) {
        return this.renderColumnWithCustomerAddress(column, row)
      }
      
      // 客户联系人
      if (formType == ConnectorFieldTypeEnum.Linkman) {
        return this.renderColumnWithCustomerLinkman(column, row)
      }
      
      // 服务部门
      if (column.fieldName == ConnectorFieldTypeEnum.Tags) {
        return this.renderTag(column, row)
      }
      
      // 地址
      if (formType == ConnectorFieldTypeEnum.Address) {
        return this.renderColumnWithAddress(column, row)
      }
      
      // 操作
      if (column.fieldName == ConnectorCardMultiFixedFieldNameEnum.Operation) {
        return this.renderOperation(row)
      }
      
      return this.renderColumnWithCommon(column, row)
    },
    /**
     * @description: 渲染通用字段
     * @param {ConnectorField} column 列
     * @param {any} row 行数据
     * @return {VNode} 元素
     */
    renderColumnWithCommon(column: ConnectorField, row: any): VNode {
      
      // 是否是系统字段
      const isSystem = isSystemFiled(column)
      // 字段类型
      const formType = column.formType || ''
      // 字段名称
      const fieldName = getFieldName(column)
      // 值
      const value = row[fieldName]
      
      return (
        <div>
          { formatFormFieldItem(column, value) }
        </div>
      )
      
    },
    /** 
     * @description 渲染 用户名
    */
    renderUserName(value: string, staffId: string) {
      
      const isShowOpenData = isOpenData && staffId
      
      return (
        <div>
          {isShowOpenData ? (
            <open-data type="userName" openid={staffId}></open-data>
          ) : (
            value
          )}
        </div>
      )
    },
    /* 人员类型 */
    renderColumnWithUser(column: ConnectorField, row: Record<string, any>): any {
      
      const user: LoginUser | any = row?.[column.fieldName || ''] || {}
      
      // 单选人员
      if(isOpenData && user.staffId) {
        return (<span><open-data type="userName" openid={user.staffId}></open-data></span>)
      }
      
      // 多选人员
      if (isOpenData && isArray(user)) {
        return (
          user.map((item: LoginUser) => {
            return <open-data type="userName" openid={item.staffId}></open-data>
          })
        )
      }
      
      return user?.displayName || user?.name || ''
    },
    /* 位置类型 */
    renderColumnWithLocation(column: ConnectorField, row: Record<string, any>): string {
      const location: Record<string, any> = row?.[column.fieldName || ''] || {}
      return location?.address || ''
    },
    /* 日期类型 */
    renderColumnWithDateTime(column: ConnectorField, row: Record<string, any>): string {
      
      const fieldName: string = column.fieldName || ''
      
      return fmt_datetime(row?.[fieldName])
    },
    /* 编号 */
    renderColumnWithSerialNumber(column: ConnectorField, row: Record<string, any>) {
      
      const serialNumber: number = row?.[column.fieldName || ''] || ''
      
      return (
        <div>
          { serialNumber }
        </div>
      )
      
    },
    /* 客户类型 */
    renderColumnWithCustomer(column: ConnectorField, row: Record<string, any>) {
      
      const customers = row?.[column.fieldName || ''] || []
      const customer = (
        isArray(customers) ? customers[0] || {} : customers
      ) || {}
      
      const classNames = 'view-detail-btn'
      
      const customerId = customer?.id || ''
      const customerName = customer?.name || ''
      
      return (
        <div
          class={classNames}
          onClick={() => openTabForCustomerView(customerId) }
        >
          { customerName }
        </div>
      )
    },
    /* 产品类型 */
    renderColumnWithProduct(column: ConnectorField, row: Record<string, any>) {
      
      let products: ConnectorServerValueProductType[] = row?.[column.fieldName || ''] || []
      
      if (isNotArray(products)) {
        products = [products as unknown as ConnectorServerValueProductType]
      }
      
      const classNames = 'view-detail-btn'
      
      const content = products.map((item: ConnectorServerValueProductType) => {
        return (
          <div class="connector-card-multi-table-product-row-item">
            <div
              class={classNames}
              onClick={() => openTabForProductView(item.id) }
            >
              { item.name }
            </div>
            <span class="connector-card-multi-table-product-row-text">
              ,
            </span>
          </div>
        )
      })
      
      return (
        <div class="connector-card-multi-table-product-row">
          { content }
        </div>
      )
    },
    /* 关联客户类型 */
    renderColumnWithRelatedCustomers(column: ConnectorField, row: Record<string, any>) {
      
      let customers: ConnectorServerValueRelatedCustomersType = row?.[column.fieldName || ''] || []
      
      if (isNotArray(customers)) {
        customers = [customers as unknown as ConnectorServerValueCustomerType]
      }
      
      const classNames = 'view-detail-btn'
      
      const content = customers.map((item: ConnectorServerValueCustomerType) => {
        return (
          <div class="connector-card-multi-table-customer-row-item">
            <div
              class={classNames}
              onClick={() => openTabForCustomerView(item.id) }
            >
              { item.name }
            </div>
            <span class="connector-card-multi-table-customer-row-text">
              ,
            </span>
          </div>
        )
      })
      
      return (
        <div class="connector-card-multi-table-customer-row">
          { content }
        </div>
      )
    },
    /* 关联工单类型 */
    renderColumnWithRelatedTasks(column: ConnectorField, row: Record<string, any>) {
      
      let tasks: Record<string, any>[] = row?.[column.fieldName || ''] || []
      
      if (isNotArray(tasks)) {
        tasks = [tasks as unknown as Record<string, any>]
      }
      
      const classNames = 'view-detail-btn'
      
      const content = tasks.map((item: Record<string, any>) => {
        return (
          <div class="connector-card-multi-table-task-row-item">
            <div
              class={classNames}
              onClick={() => openTabForTaskView(item.taskId) }
            >
              { item.taskNo }
            </div>
            <span class="connector-card-multi-table-task-row-text">
              ,
            </span>
          </div>
        )
      })
      
      return (
        <div class="connector-card-multi-table-task-row">
          { content }
        </div>
      )
    },
    /* 客户地址 */
    renderColumnWithCustomerAddress(column: ConnectorField, row: Record<string, any>) {
      
      const addressList = row?.[column.fieldName || ''] || []
      const address = (
        isArray(addressList) ? addressList[0] || {} : addressList
      ) || {}
      
      return new TaskAddress(address).toString() || address?.name || ''
    },
    /* 客户联系人 */
    renderColumnWithCustomerLinkman(column: ConnectorField, row: Record<string, any>) {
      
      const linkmanList = row?.[column.fieldName || ''] || []
      const linkman = (
        isArray(linkmanList) ? linkmanList[0] : linkmanList
      ) || {}
      
      const linkmanName = linkman?.name || ''
      
      return (
        <div>
          { linkmanName }
        </div>
      )
    },
    /* 服务部门 */
    renderTag(column: ConnectorField, row: Record<string, any>) {
      
      const tags = row?.[column.fieldName || ''] || []
      const tag = (
        isArray(tags) ? tags[0] : tags
      ) || {}
      
      const tagName = tag?.tagName || tag?.name
      
      return (
        <div>
          { tagName }
        </div>
      )
    },
    /* 地址类型 */
    renderColumnWithAddress(column: ConnectorField, row: Record<string, any>): string {
      const address: any = row?.[column.fieldName || ''] || {}
      return new TaskAddress(address).toString()
    },
    /**
     * @description 渲染 操作
     */
    renderOperation(row: Record<string, any>) {
      console.log('row', this.showDeleteButton )
      return (
        <div>
          { this.showDeleteButton && this.renderOperationDeleteButton(row) }
        </div>
      )
    },
    /**
     * @description 渲染 操作 删除按钮
     */
    renderOperationDeleteButton(row: Record<string, any>) {
      return (
        <el-button
            type="text"
            onClick={() => this.onConnectorCardItemDeleteHandler(row)}
        >
          {t('common.base.delete')}
        </el-button>
      )
    },
    handleSelectionChange(val) {
      // console.log("val", val, this.isMulti)
      // 判断是否支持多选
      if(this.isMulti) {
        // this.multipleSelection = val
        this.$emit("selectionChange", val)
        return
      }
      const current = val[val.length -1]
      if(val.length > 1) {
        this.$refs.connectorMultipleTable.clearSelection()
        this.$refs.connectorMultipleTable.toggleRowSelection(current)
      }
      // this.multipleSelection = [current];
      this.$emit("selectionChange", [current])
    },
    toggleRowSelection({ selections }) {
      // console.log("row", selections)
      this.$refs?.connectorMultipleTable?.clearSelection()
      selections && selections.forEach(row => {
        this.$refs?.connectorMultipleTable?.toggleRowSelection(row)
      })
    }
  },
  render(h: CreateElement) {
    
    const scopedSlots = this.loading ? {} : {
      empty: () => this.renderTableAppendSlot()
    }

    const classNames = {
      [ConnectorModuleComponentNameEnum.ConnectorModuleConnectorCardMultiCardTable]: true,
      [ComponentNameEnum.FormBuilderTable]: this.formTableColumns.length,
    }
    
    return (
      <div class={classNames}>
        <el-table
          border
          class={ this.isMulti ? 'bbx-normal-list-box' : 'bbx-normal-list-box connector-table-select-single'}
          data={this.tableValues || []}
          headerRowClassName='base-table-header-v3'
          rowClassName='base-table-row-v3'
          row-key = {(row: { bizId: any }) => row.bizId + '-' + this.randomStr()}
          stripe
          scopedSlots={scopedSlots}
          onSelect={this.handleSelectionChange}
          on-select-all={this.handleSelectionChange}
          onCell-click={this.onTableCellClickHandler}
          ref='connectorMultipleTable'
          max-height="460px"
        >
          {
            this.showIndex ? (<el-table-column label={t('common.fields.orderNo.displayName')} type="index" width="50" />) : (<el-table-column type="selection" width="55"/>)
          }
          {
            (this.fields as ConnectorField[]).map((column: ConnectorField) => {
              return (
                <el-table-column
                  // @ts-ignore
                  fixed={column.fixed}
                  label={column.label}
                  key={column.field || column.fieldName}
                  width={column.width}
                  minWidth={column.minWidth ? `${column.minWidth}px` : TableColumnDefaultWidth}
                  prop={column.field}
                  resizable
                  show-overflow-tooltip
                >
                  { (scope: any) => this.renderTableColumnField(h, scope, column) }
                </el-table-column>
              )
            })
          }


          {/* start 其他自定义列 */}
          {this.formTableColumns.length && (
            <FormBuilderTableColumnsView
              columns={this.formTableColumns}
              data={this.values}
            ></FormBuilderTableColumnsView>
          )}
          {/* end 其他自定义列 */}

          <div slot='append'></div>
          <div slot="empty">
            <div class={ this.loading ? 'block-hide' : 'block-show'}>
              <BaseListForNoData  notice-msg={t('common.base.tip.noData')}></BaseListForNoData>
            </div>
          </div>
          
        </el-table>
      </div>
    )
  }
})
